﻿using System;
using System.Data;
using TimKen.DataEntity;
using System.Collections.Generic;
using TimKen.DataAccess;


namespace TimKen.BussLogic
{
    /// <summary>
    /// 产品分类业务逻辑操作类
    /// </summary>
    public class PCategoryManager : BaseManager
    {
        private readonly TimKen.DataAccess.PCategoryDAO dal = new TimKen.DataAccess.PCategoryDAO();
        private readonly TimKen.DataAccess.POptionRelPCategoryDAO ortdal = new TimKen.DataAccess.POptionRelPCategoryDAO();
        private readonly TimKen.DataAccess.POptionDAO optiondal = new TimKen.DataAccess.POptionDAO();

        /// <summary>
        /// “其它" 产品分类的ID，此iD已经写死，值就是在SQLSErver中能够存储的整型最大值　
        /// </summary>
        public  const int otherCategoryID = 2147483647;

        public PCategoryManager()
        { }
        #region  成员方法
        /// <summary>
        /// 是否存在该记录
        /// </summary>
        public bool Exists(int CategoryID)
        {
            return dal.Exists(CategoryID);
        }

        public bool Exists(params PCategory[] modelList)
        {
            long CategoryCount = this.GetListCount(" (CategoryName='" + modelList[0].CategoryName + "' or CategoryName='" + modelList[1].CategoryName + "') and CategoryID<>" + modelList[0].CategoryID);
            if (CategoryCount == 0)
                return false;
            else
                return true;
        }

        public bool Exists(TimKen.DataEntity.PCategory model)
        {
            long CategoryCount = this.GetListCount(" CategoryName='" + model.CategoryName + "' and CategoryID<>" + model.CategoryID);
            if (CategoryCount == 0)
                return false;
            else
                return true;
        }

        /// <summary>
        /// 增加一条数据，成功返回true，失败返回false
        /// </summary>
        public bool Add(TimKen.DataEntity.PCategory model)
        {
            ValidMessage = "";
            bool isExists = Exists(model);
            if (isExists)
            {
                ValidMessage = GetLangString("ExistCategory"); ;
                return false;
            }
            else
            {
                dal.Add(model);
                ValidMessage = GetLangString("SaveSuccessful");
                return true;
            }
        }


        public int Add(params PCategory[] modelList)
        {
            ValidMessage = "";
            bool isExists = Exists(modelList);
            if (isExists)
            {
                ValidMessage = GetLangString("ExistCategory"); ;
                return -1;
            }
            else
            {
                //判断是否非法
                PCategory model = modelList[0];
                PCategory newParentCategory = GetModel(model.ParentID, LanguageEnum.English);
                //如果移到一个叶子结点下面，则属于非法
                if (newParentCategory != null && newParentCategory.IsLeaf == true)
                {
                    ValidMessage = GetLangString("OperationInvalid");
                    return 0;
                }
                //如果父节点是自身，则属于非法
                else if (newParentCategory != null && newParentCategory.CategoryID == model.CategoryID)
                {
                    ValidMessage = GetLangString("OperationInvalid");
                    return 0;
                }

                int newid = 1;
                string strsql = "select max(CategoryID)+1 from PCategory  WHERE CategoryID!="　+ otherCategoryID;
                object obj = DbHelperSQL.GetSingle(strsql);
                if (obj != null)
                {
                    newid = int.Parse(obj.ToString());
                }

                foreach (PCategory category in modelList)
                {
                    category.CategoryID = newid;
                    dal.Add(category);
                }
                ValidMessage = GetLangString("SaveSuccessful");
                return newid;
            }
        }




        /// <summary>
        /// 更新一条数据
        /// </summary>
        public bool Update(TimKen.DataEntity.PCategory model)
        {
            if (Exists(model))
            {
                ValidMessage = GetLangString("ExistCategory");




                return false;
            }
            else
            {
                dal.Update(model);
                ValidMessage = GetLangString("SaveSuccessful");
                return true;
            }
        }

        public bool Update(params PCategory[] modelList)
        {
            //if (Exists(modelList))
            //{
            //    ValidMessage = GetLangString("ExistCategory");
            //    return false;
            //}
            //else
            //{


                PCategory model = modelList[0];


                if (model.ParentID != 0)
                {

                    //判断更改产品类别是否违反逻辑
                    PCategory oldCategory = GetModel(model.CategoryID, LanguageEnum.English);
                    PCategory newParentCategory = GetModel(model.ParentID, LanguageEnum.English);


                    //如果移到一个叶子结点下面，则属于非法
                    if (newParentCategory.IsLeaf == true)
                    {
                        ValidMessage = GetLangString("OperationInvalid");
                        return false;
                    }

                    else if (newParentCategory.CategoryID == model.CategoryID)
                    {
                        ValidMessage = GetLangString("OperationInvalid");
                        return false;
                    }
                }





                dal.Update(modelList[0]);
                dal.Update(modelList[1]);
                ValidMessage = GetLangString("SaveSuccessful");
                return true;
           // }
        }

        public bool ChangeIsLeaf(int CategoryID, bool IsLeaf)
        {
            ValidMessage = "";
            //IsLeaf ==true ，由最底层分类转变为非最底层分类，不允许含有产品、不能有属性
            if (IsLeaf)
            {
                //如果有子产品，提示错误

                ProductManager ptm = new ProductManager();
                long childProductCount = ptm.GetProductCountByCategoryID(CategoryID);
                if (childProductCount > 0)
                {
                    ValidMessage = GetLangString("Categoryhasproduct") + GetLangString("ForbidChangeIsLeaf");
                    return false;
                }

                //如果有属性，提示错误
                POptionManager pom = new POptionManager();

                int childPOptionCount = 0;
                pom.GetSearchableListByCategory(CategoryID, (int)LanguageEnum.Chinese, "", ref childPOptionCount, 0);

                if (childPOptionCount > 0)
                {
                    ValidMessage = GetLangString("Categoryhasoption") + GetLangString("ForbidChangeIsLeaf");
                    return false;
                }
            }
            else
            {
                //IsLeaf !=false，由非最底层分类转变为最底层分类，不允许含有子分类
                //如果有子分类，提示错误
                long childCount = GetListCount("  ParentID=" + CategoryID);
                if (childCount > 0)
                {
                    ValidMessage = GetLangString("NotLeafCategory") + GetLangString("ForbidChangeIsLeaf");
                    return false;
                }

            }

            dal.ChangeIsLeaf(CategoryID);
            ValidMessage = GetLangString("DeleteSuccessful");
            return true;
        }


        /// <summary>
        /// 删除产品类别
        /// </summary>
        /// <param name="CategoryID"></param>
        public bool Delete(int CategoryID)
        {
            ValidMessage = "";
            //判断是否是孤立分类（无子产品、无子分类、无属性）

            //如果有子分类，提示错误
            long childCount = GetListCount("  ParentID=" + CategoryID);
            if (childCount > 0)
            {
                ValidMessage = GetLangString("NotLeafCategory") + GetLangString("ForbidDelete");
                return false;
            }

            //如果有子产品，提示错误

            ProductManager ptm = new ProductManager();
            long childProductCount = ptm.GetProductCountByCategoryID(CategoryID);
            if (childProductCount > 0)
            {
                ValidMessage = GetLangString("Categoryhasproduct") + GetLangString("ForbidDelete");
                return false;
            }

            //如果有属性，提示错误
            POptionManager pom = new POptionManager();

            int childPOptionCount = 0;
            pom.GetSearchableListByCategory(CategoryID, (int)LanguageEnum.Chinese, "", ref childPOptionCount, 0);

            if (childPOptionCount > 0)
            {
                ValidMessage = GetLangString("Categoryhasoption") + GetLangString("ForbidDelete");
                return false;
            }

            //无上述问题，执行删除

            dal.Delete(CategoryID);
            ValidMessage = GetLangString("DeleteSuccessful");
            return true;
        }

        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public TimKen.DataEntity.PCategory GetModel(int CategoryID, LanguageEnum LanguageID)
        {
            return dal.GetModel(CategoryID, (int)LanguageID);
        }



        /// <summary>
        /// 获得数据列表
        /// </summary>
        public DataSet GetList(string strWhere)
        {
            return dal.GetList(strWhere);
        }

        public DataSet GetListAndKwd(int LanguageID)
        {
            return dal.GetListAndKwd(LanguageID);
            //return null;
        }

        public DataSet GetListAndKwd(int LanguageID, int ParentID)
        {
            return dal.GetListAndKwd(LanguageID, ParentID);
            //return null;
        }

        public DataSet GetPHotKeyWords(int LanguageID, int ParentID)
        {
            return dal.GetPHotKeyWords(LanguageID, ParentID);
            //return null;
        }

        public DataSet GetTreeGrid(int LanguageID, int ParentID)
        {
            return dal.GetTreeGrid(LanguageID, ParentID);
            //return null;
        }

        public bool SetPHotKeyWords(string action, int sort, int languageID, int CategoryID)
        {
            return dal.SetPHotKeyWords(action, sort, languageID, CategoryID);
        }

        /// <summary>
        /// 获得数据列表
        /// </summary>
        public DataSet GetAllList()
        {
            return GetList("");
        }

        /// <summary>
        /// 获得数据列表
        /// </summary>
        //public DataSet GetList(int PageSize,int PageIndex,string strWhere)
        //{
        //return dal.GetList(PageSize,PageIndex,strWhere);
        //}


        /// <summary>
        /// 获取符合条件的数量
        /// </summary>
        /// <param name="strWhere"></param>
        /// <returns></returns>
        public long GetListCount(string strWhere)
        {
            return dal.GetListCount(strWhere);
        }


        /// <summary>
        /// 得到最大ID
        /// </summary>
        public int GetMaxId()
        {
            return dal.GetMaxId();
        }


        #region 获取所有的父类
        /// <summary>
        /// 返回产品分类所有父类
        /// </summary>
        /// <param name="categoryID">分类ID</param>
        /// <param name="languageID">语言ID</param>
        /// <returns>返回结构 categoryname:categoryid,categoryname:categoryid,categoryname:categoryid,</returns>
        public string GetAllParent(int categoryID, int languageID)
        {
            return dal.GetAllParent(categoryID, languageID);
        }
        #endregion

        #endregion  成员方法

        /// <summary>
        /// 返回分类的子列表
        /// </summary>
        /// <param name="categoryID">分类ID</param>
        /// <param name="languageID">语言ID</param>
        /// <returns></returns>
        public DataSet GetChild(int categoryID, int languageID, int brandID)
        {
            return dal.GetChild(categoryID, languageID, brandID);
        }


        public DataSet GetUncle(int categoryID, int languageID)
        {
            PCategory category = GetModel(categoryID, (LanguageEnum)languageID);

            if (category.ParentID == 0)
                return null;




            return dal.GetList("  ParentID=" + category.ParentID + " AND CategoryID !=" + category.CategoryID + " AND LanguageID=" + languageID);
        }

        public DataSet CategoryListSite(int cid, int languageID)
        {
            return dal.CategoryListSite(cid, languageID);
        }

        public DataSet GetAllLeafCategory(String where)
        {
            return dal.GetList(" IsLeaf=1 AND " + where);
        }

        public DataSet GetRoot(string LanguageWhereStr)
        {
            return dal.GetList(LanguageWhereStr + " AND ParentID=0");
        }

        /// <summary>
        /// 获取某一类下的子类
        /// </summary>
        /// <param name="pageSize"></param>
        /// <param name="currentIndex"></param>
        /// <param name="parentID"></param>
        /// <param name="languageID"></param>
        /// <returns></returns>
        public DataSet GetCategoryPageList(int pageSize, int PageIndex, int parentID, int languageID)
        {
            return dal.GetCategoryPageList(pageSize, PageIndex, parentID, languageID);
        }

        /// <summary>
        /// 获取分类图片,如果此分类没有图片,则获取上级分类的图片,类推
        /// </summary>
        /// <param name="CategoryID"></param>
        /// <returns></returns>
        public string GetCategoryImage(int CategoryID)
        {

            PCategory c = GetModel(CategoryID, LanguageEnum.Chinese);

            if (CategoryID == 0)
                return "/images/defaultcategoryimage.jpg";
            if (string.IsNullOrEmpty(c.CategoryImage))
                return GetCategoryImage(c.ParentID);

            return c.CategoryImage;

        }




        #region 属性管理
        /// <summary>
        /// 为类型增加属性
        /// </summary>
        /// <param name="optionIDs"></param>
        /// <param name="CategoryID"></param>
        public void AddOptionToCategory(IList<POptionRelPCategory> orts)
        {
            foreach (POptionRelPCategory ort in orts)
            {
                if (!ortdal.Exists(ort.OptionID, ort.CategoryID))
                {
                    ortdal.Add(ort);
                }
            }
        }

        public void AddOptionToCategory(int optionID, int CategoryID, bool isSearchAble)
        {
            POptionRelPCategory ort = new POptionRelPCategory();
            ort.CategoryID = CategoryID;
            ort.OptionID = optionID;
            ort.AttributeIndex = isSearchAble;
            ortdal.Add(ort);
        }
        public void UpdateOptionInCategory(POptionRelPCategory ort)
        {
            ortdal.Update(ort);
        }
        /// <summary>
        /// 从类型移除属性
        /// </summary>
        /// <param name="optionids"></param>
        /// <param name="CategoryID"></param>
        public void RemoveOptionFromCategory(string optionids, string CategoryID)
        {
            ortdal.Delete(optionids, CategoryID);
        }
        public void UpdateSortOrder(string CategoryID, string optionID, int sortOrder)
        {
            ortdal.UpdateSortOrder(CategoryID, optionID, sortOrder);
        }
        /// <summary>
        /// 根据产品类型获取相关属性分页
        /// </summary>
        /// <param name="CategoryID">类型id</param>
        /// <param name="languageid">语言id</param>
        /// <returns></returns>
        public DataSet GetOptionByCategory(int pagesize, int pageindex, string CategoryID, string languageid)
        {
            return optiondal.GetOptionByType(pagesize, pageindex, CategoryID, languageid);
        }
        /// <summary>
        /// 返回该类型的前1000条数据。
        /// </summary>
        /// <param name="CategoryID">类型ID</param>
        /// <param name="languageid">语言ID</param>
        /// <returns></returns>
        public DataSet GetOptionByCategory(string CategoryID)
        {
            return optiondal.GetOptionByType(1000, 1, CategoryID, "-1");
        }

        public DataSet GetOptionNotInCategory(int pagesize, int pageindex, string CategoryID, string languageid, string fieldType, string attrName)
        {
            return optiondal.GetOptionNotInType(pagesize, pageindex, CategoryID, languageid, fieldType, attrName);
        }

        #endregion

    }
}
